package com.arsn.myf.common.handle;

import com.arsn.myf.common.util.auth.AuthUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatis 数据插入更新处理器
 * @author zhongrj
 * @date 2022-12-14
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 插入操作处理器
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        //获取属性名
        String[] getterNames = metaObject.getGetterNames();
        //遍历
        for (String name : getterNames) {
            if (name.equals("createUser")){
                setFieldValByName("createUser",AuthUtil.getUserId(),metaObject);
            }
            if (name.equals("createTime")){
                setFieldValByName("createTime",new Date(),metaObject);
            }
            if (name.equals("updateUser")){
                setFieldValByName("updateUser",AuthUtil.getUserId(),metaObject);
            }
            if (name.equals("updateTime")){
                setFieldValByName("updateTime",new Date(),metaObject);
            }
        }
    }

    /**
     * 更新操作处理器
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //获取属性名
        String[] getterNames = metaObject.getGetterNames();
        //遍历
        for (String name : getterNames) {
            if (name.equals("updateUser")){
                setFieldValByName("updateUser",AuthUtil.getUserId(),metaObject);
            }
            if (name.equals("updateTime")){
                setFieldValByName("updateTime",new Date(),metaObject);
            }
        }
    }
}
